#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>

using namespace cv; //Must Need Write cv
using namespace std;

/*
 * ./opencv_at_demo1 <image1>
 *
 */

int main(int argc, char** argv)
{

    if(argc != 2)
    {
        printf(" Usage : %s <image1> \n", argv[0]);
        return -1;
    }
    
    //1.将输入图像转化为单通道灰度图
    Mat img_gray = imread(argv[1], 0);// falg = 0;单通道灰度图像
    if (img_gray.empty())
    {
        printf("can not get %s \n", argv[1]);
        return -1;
    }
    else
    {
        printf("width = %d, height = %d, channel = %d \n", img_gray.cols, img_gray.rows, img_gray.channels());
    }

    
    Mat canny_img;
    //2.使用canny进行边缘检测，获取输出的边缘图像
    Canny(img_gray, canny_img, 50, 150);
    
    if (canny_img.empty())
    {
        printf("canny img err \n");
        return -1;
    }
    else
    {
        printf("width = %d, height = %d, channel = %d \n", canny_img.cols, canny_img.rows, canny_img.channels());
    }

    
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    //3.对边缘图像进行轮廓检测，使用 findContours
    findContours(canny_img, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE, Point());
    printf("contours = %d\n", (int)contours.size());
    
    // 修复1: 初始化输出图像
    Mat out_img = Mat::zeros(canny_img.size(), CV_8UC3); // 创建彩色输出图像
    
    // 修复2: 检查轮廓是否为空
    if (contours.empty()) {
        printf("No contours found!\n");
        return -1;
    }
    
    //4.绘制轮廓
    for (int i = 0; i < contours.size(); i++ )
    {
         // 修复3: 确保轮廓不为空
        if (!contours[i].empty()) {
            drawContours(out_img, contours, i, Scalar(0, 255, 0), 1, LINE_8); // 绿色轮廓
        }   
    }

    // 修复4: 检查输出图像是否有效
    if (out_img.empty()) {
        printf("Output image is empty!\n");
        return -1;
    }
    
    string output_filename;
    output_filename = "drawLK.jpg";
    
    bool success = imwrite(output_filename, out_img);
    if (!success) {
        printf("Failed to save image!\n");
        return -1;
    }

    printf("Image saved as: %s\n", output_filename.c_str());
    return 0;
}


